package cn.com.aiouyi.service.impl;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;

import cn.com.aiouyi.entity.Article;
import cn.com.aiouyi.entity.ArticleClass;
import cn.com.aiouyi.service.ArticleClassService;
import cn.com.aiouyi.service.ArticleService;
import cn.com.aiouyi.service.LinkService;
import cn.com.aiouyi.util.AssertUtils;
import cn.com.aiouyi.vo.Link;

/**
 * Service - link
 * @author hanson
 *
 */
@Service("linkServiceImpl")
@Transactional
public class LinkServiceImpl implements LinkService{

	@Resource(name = "articleServiceImpl")
	private ArticleService articleService;
	@Resource(name = "articleClassServiceImpl")
	private ArticleClassService articleClassService;
	
	@Override
	public void validAndFill(Link link) {
		AssertUtils.notNull(link);
		AssertUtils.notNull(link.getType());
		
		switch(link.getType()){
			case none:{
				break;
			}
			case url:{
				Link.UrlData data = JSON.parseObject(link.getData(), Link.UrlData.class);
				if(StringUtils.isEmpty(data.getUrl())){
					throw new IllegalArgumentException("链接不能为空");
				}
				
				link.setData(JSON.toJSONString(data));
				break;
			}
			case article:{
				Link.ArticleData data = JSON.parseObject(link.getData(), Link.ArticleData.class);
				Article article = null;
				if(data.getId() != null){
					article = articleService.find(data.getId());
				}
				if(article == null){
					throw new IllegalArgumentException("专题不存在");
				}
				data.setId(article.getId());
				data.setTitle(article.getTitle());
				
				link.setData(JSON.toJSONString(data));
				break;
			}
			case articleClass:{
				Link.ArticleClassData data = JSON.parseObject(link.getData(), Link.ArticleClassData.class);
				ArticleClass articleClass = null;
				if(data.getId() != null){
					articleClass = articleClassService.find(data.getId());
				}
				if(articleClass == null){
					throw new IllegalArgumentException("文章分类不存在");
				}
				data.setId(articleClass.getId());
				data.setName(articleClass.getName());
				
				link.setData(JSON.toJSONString(data));
				break;
			}
			case fileDownload:{
				break;
			}
			default:
				break;
		}
	}

	@Override
	public Article extractArticle(Link link) {
		if(link == null || link.getType() != Link.Type.article){
			return null;
		}
		Link.ArticleData data = JSON.parseObject(link.getData(), Link.ArticleData.class);
		Article article = null;
		if(data.getId() != null){
			article = articleService.find(data.getId());
		}
		return article;
	}
}
